package centerberg.game;

import centerberg.engine.Drawable;
import centerberg.engine.Engine;
import centerberg.engine.PhysicsObject;
import centerberg.engine.Solid;
import centerberg.engine.Texture;

import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.util.Map;

/**
 * Solid ground.
 * 
 * @author Andreas Svanberg
 */
public class Ground extends Solid implements Drawable
{
    /**
     * The texture of this object.
     */
    protected Texture texture;
    
    private Ground(Shape shape)
    {
        super(shape);
    }
    
    /**
     * {@inheritDoc}. Does nothing since ground is simply static.
     */
    public void collided(PhysicsObject other)
    {
        
    }
    
    /**
     * Creates a new ground object with the given attributes.
     * Used by the loader to create them based on XML-data.
     * 
     * @param attributes a map of attributes determining
     *                   how to create the object
     */
    public static Ground create(Map<String, String> attributes)
    {
        int x = Integer.parseInt(attributes.get("x"));
        int y = Integer.parseInt(attributes.get("y"));
        int w = Integer.parseInt(attributes.get("width"));
        int h = 24;
        if (attributes.containsKey("height"))
            Integer.parseInt(attributes.get("height"));
        
        Shape shape = new Rectangle2D.Double(x, y, w, h);
        Ground ground = new Ground(shape);
        
        Texture texture;
        if (attributes.containsKey("texture"))
            texture = Engine.getInstance().resourceManager.textures
                .getTiledTexture(attributes.get("texture"), w, h);
        else
            texture = Engine.getInstance().resourceManager.textures
                .getTiledTexture("ground", w, h);
        
        texture.translate(x, y);
        ground.texture = texture;
        
        if (attributes.containsKey("angle"))
        {
            int angle = -Integer.parseInt(attributes.get("angle"));
            if (angle >= 90 || angle <= -90)
                throw new IllegalArgumentException("Invalid angle. Expected (-90, 90); got: " + angle);
            
            double shear = angle / 45.0;
            
            ground.getPhysicalRepresentation().shear(shear);
            ground.texture.shear(shear);
        }
        
        return ground;
    }
    
    /**
     * {@inheritDoc}
     */
    public Texture getTexture()
    {
        return texture;
    }
    
    /**
     * {@inheritDoc}. Does nothing since ground is static.
     */
    public void tick(double elapsed)
    {
    }
    
    /**
     * {@inheritDoc}.
     */
    public void translated(double dx, double dy)
    {
        texture.translate(dx, dy);
    }
}